#include "DirectInput.h"

CDInput::CDInput()
{
	m_pDirectInput	= NULL;
	m_pKeyboard		= NULL;
	m_pMouse		= NULL;
	m_Position.x	= 0;
	m_Position.y	= 0;
}

BOOL CDInput::InitDirectInput(HWND hWnd, HINSTANCE	hInstance)
{
	HRESULT	hr;

	hr = DirectInput8Create(hInstance, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&m_pDirectInput, NULL);

	// create keyboard device
	hr &= m_pDirectInput->CreateDevice(GUID_SysKeyboard, &m_pKeyboard, NULL);

	hr &= m_pKeyboard->SetDataFormat(&c_dfDIKeyboard);

	hr &= m_pKeyboard->SetCooperativeLevel(hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE); 

	DIPROPDWORD dipdw;

    dipdw.diph.dwSize       = sizeof(DIPROPDWORD);
    dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
    dipdw.diph.dwObj        = 0;
    dipdw.diph.dwHow        = DIPH_DEVICE;
    dipdw.dwData            = 256;

	hr &= m_pKeyboard->SetProperty( DIPROP_BUFFERSIZE, &dipdw.diph );

	hr &= m_pKeyboard->Acquire();

	// Create mouse device
	ZeroMemory(&m_MouseState, sizeof(m_MouseState));	
	hr &= m_pDirectInput->CreateDevice(GUID_SysMouse, &m_pMouse, NULL);

	hr &= m_pMouse->SetDataFormat(&c_dfDIMouse);

	hr &= m_pMouse->SetCooperativeLevel(hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);

	hr &= m_pMouse->Acquire();

	if (hr != D3D_OK)
		return FALSE;

	return TRUE;
}

void CDInput::ProcessInput(HWND hWnd)
{
	HRESULT hr;

	hr = m_pKeyboard->GetDeviceState( sizeof(m_KeyboardState), m_KeyboardState);

	if( FAILED(hr) )
	{
		// Keyboard lost, zero out keyboard data structure.
		ZeroMemory(m_KeyboardState, sizeof(m_KeyboardState));

		 // Try to acquire for next time we poll.
		hr = m_pKeyboard->Acquire();
	}

	hr = m_pMouse->GetDeviceState(sizeof(m_MouseState), &m_MouseState);

	if( FAILED(hr) )
	{
		// Keyboard lost, zero out keyboard data structure.
		ZeroMemory(&m_MouseState, sizeof(m_MouseState));

		 // Try to acquire for next time we poll.
		hr = m_pMouse->Acquire();
	}


	DWORD dwElements = 256;
	m_pKeyboard->GetDeviceData( sizeof(DIDEVICEOBJECTDATA), m_KeyEvents, &dwElements, 0 );

	// Scan through all data, check if the key is pressed or released
	for( DWORD i = 0; i < dwElements; i++ ) 
	{
		int KeyCode = m_KeyEvents[i].dwOfs;
		int KeyState = m_KeyEvents[i].dwData;
		if ( (KeyState & 0x80) > 0)
			OnKeyDown(KeyCode);
		else 
			OnKeyUp(KeyCode);
	}
}

BOOL CDInput::isKeyDown(int keycode)
{
	return (m_KeyboardState[keycode] & 0x80) > 0;
}


void CDInput::OnKeyDown(int keycode)
{
}

void CDInput::OnKeyUp(int keycode)
{
}


void CDInput::Release()
{
	if (m_pKeyboard)
	{
		m_pKeyboard->Release();
		m_pKeyboard = NULL;
	}

	if (m_pDirectInput)
	{
		m_pDirectInput->Release();
		m_pDirectInput = NULL;
	}

	if (m_pMouse)
	{
		m_pMouse->Release();
		m_pMouse = NULL;
	}
}